/**
 * 将文件加上_bak的后缀作为备份
 * @param ip
 * @param fileName
 */
void call(String ip ,String fileName) {

    def fileNameBak = getFileBakName(fileName)
    print("备份文件名:${fileNameBak}")
  withCredentials([sshUserPrivateKey(credentialsId: 'ssh_key',  // 凭证 ID
          keyFileVariable: 'SSH_KEY',
          usernameVariable: 'USER')]) {
    sh(script: """
       
                             SSH_DIR="/var/jenkins_home/.ssh"                                      # Jenkins 容器可写的 .ssh 目录
                             if ssh -o UserKnownHostsFile=\$SSH_DIR/known_hosts \\
                             -i \$SSH_KEY \\
                           \$USER@${ip}  \\
                             "[ -f \\"${fileName}\\" ]"; then
                          
                              ssh -o UserKnownHostsFile=\$SSH_DIR/known_hosts \\
                             -i \$SSH_KEY \\
                           \$USER@${ip}  \\ " mv -f ${fileName} ${fileNameBak}"
                            echo "${fileName}已备份"
                        else
                            echo "${fileName}不存在无法备份！"
                           
                        fi
                       
                    """)
  }


}
/**
 * 获取备份文件名
 * @param fileName
 * @return
 */
String getFileBakName(String fileName){
    int lastDotIndex = fileName.lastIndexOf('.')
    if (lastDotIndex > 0) {
        return  fileName.substring(0, lastDotIndex) + '_bak' + fileName.substring(lastDotIndex)
    }else{
        return fileName
    }

}
